package fm.interceptor;

import fm.cache.ConfigCache;
import fm.dto.SystemUser;
import fm.dto.NeiyiUser;
import fm.web.CurrentRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * class name： fm.interceptor.TokenInterceptor
 * author： CM
 * create time： 2016/3/12.
 */
public class RequestInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            modelAndView.addObject("WEB_TITLE", ConfigCache.getConfig("WEB_TITLE"));
            Subject subject = SecurityUtils.getSubject();

            if (subject.isAuthenticated()) {
                Object user = CurrentRequest.getCurrentLoginUser();
                if (user instanceof NeiyiUser) {
                    modelAndView.addObject("username", ((NeiyiUser) user).getCompanyName());
                    modelAndView.addObject("uid", ((NeiyiUser) user).getId());
                    modelAndView.addObject("userType", ((NeiyiUser) user).getUserType());
                    modelAndView.addObject("userLogo", ((NeiyiUser) user).getUserLogo()
                    );
                }
                else if (user instanceof SystemUser) {
                    modelAndView.addObject("username", ((SystemUser) user).getName());
                    modelAndView.addObject("uid", ((SystemUser) user).getId());
                    modelAndView.addObject("userType", 0);
                }

            }


            String fileUploadProxyServer = ConfigCache.getConfig("FILE_UPLOAD_PROXY_SERVER",null);
            modelAndView.addObject("file_upload_proxy_server",fileUploadProxyServer);


        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
